import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getAdminDashboardData, getAdminMerchants, getAdminProducts, getAdminOrders, getAdminUsers } from '@/api/admin'

/**
 * 管理员状态管理
 */
export const useAdminStore = defineStore('admin', () => {
  // 仪表盘数据
  const dashboardData = ref({
    totalOrders: 0,
    totalUsers: 0,
    totalProducts: 0,
    totalRevenue: 0,
    recentOrders: [],
    recentUsers: [],
    salesData: [],
    categoryData: []
  })

  // 商户数据
  const merchants = ref([])
  const merchantsLoading = ref(false)
  const merchantsTotal = ref(0)

  // 商品数据
  const products = ref([])
  const productsLoading = ref(false)
  const productsTotal = ref(0)

  // 订单数据
  const orders = ref([])
  const ordersLoading = ref(false)
  const ordersTotal = ref(0)

  // 用户数据
  const users = ref([])
  const usersLoading = ref(false)
  const usersTotal = ref(0)

  // 获取仪表盘数据
  const fetchDashboardData = async () => {
    try {
      const data = await getAdminDashboardData()
      dashboardData.value = data
    } catch (error) {
      console.error('获取仪表盘数据失败', error)
    }
  }

  // 获取商户列表
  const fetchMerchants = async (params = {}) => {
    try {
      merchantsLoading.value = true
      const { data, total } = await getAdminMerchants(params)
      merchants.value = data
      merchantsTotal.value = total
    } catch (error) {
      console.error('获取商户列表失败', error)
    } finally {
      merchantsLoading.value = false
    }
  }

  // 获取商品列表
  const fetchProducts = async (params = {}) => {
    try {
      productsLoading.value = true
      const { data, total } = await getAdminProducts(params)
      products.value = data
      productsTotal.value = total
    } catch (error) {
      console.error('获取商品列表失败', error)
    } finally {
      productsLoading.value = false
    }
  }

  // 获取订单列表
  const fetchOrders = async (params = {}) => {
    try {
      ordersLoading.value = true
      const { data, total } = await getAdminOrders(params)
      orders.value = data
      ordersTotal.value = total
    } catch (error) {
      console.error('获取订单列表失败', error)
    } finally {
      ordersLoading.value = false
    }
  }

  // 获取用户列表
  const fetchUsers = async (params = {}) => {
    try {
      usersLoading.value = true
      const { data, total } = await getAdminUsers(params)
      users.value = data
      usersTotal.value = total
    } catch (error) {
      console.error('获取用户列表失败', error)
    } finally {
      usersLoading.value = false
    }
  }

  // 计算有多少条新订单
  const newOrdersCount = computed(() => {
    return orders.value.filter(order => order.status === 'new').length
  })

  return {
    dashboardData,
    merchants,
    merchantsLoading,
    merchantsTotal,
    products,
    productsLoading,
    productsTotal,
    orders,
    ordersLoading,
    ordersTotal,
    users,
    usersLoading,
    usersTotal,
    newOrdersCount,
    fetchDashboardData,
    fetchMerchants,
    fetchProducts,
    fetchOrders,
    fetchUsers
  }
}) 
 